package lium.lbs.lbsim.activity

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.support.v4.content.ContextCompat
import android.view.Gravity
import android.view.View
import android.widget.Toast
import com.buz.hjcdriver.bean.AResultBean
import com.buz.hjcdriver.bean.GetUserInfoResultBean
import com.lmlibrary.Constants
import lium.lbs.lbsim.utils.UserUtils
import com.lmlibrary.bean.ResponseBean
import lium.lbs.lbsim.utils.callbck.DialogCallback
import lium.lbs.lbsim.utils.callbck.JsonCallback
import lium.lbs.lbsim.utils.SpUtils
import lium.lbs.lbsim.utils.ToastUtils
import com.luck.picture.lib.PictureSelector
import com.luck.picture.lib.config.PictureConfig
import com.luck.picture.lib.config.PictureMimeType
import com.lzy.okgo.model.Response
import com.tbruyelle.rxpermissions2.RxPermissions
import kotlinx.android.synthetic.main.activity_changenamehead.*
import lium.lbs.lbsim.R
import lium.lbs.lbsim.jgchat.pickerimage.PickImageActivity
import lium.lbs.lbsim.utils.IAlertDialog
import net.arvin.selector.SelectorHelper
import net.arvin.selector.data.ConstantData
import java.io.File
import java.util.HashMap

class ChangeNameHeadActivity: BaseActivity() {

    override fun getLayoutId(): Int { return R.layout.activity_changenamehead  }
    var isInitPhotoButton=false

    override fun initView(savedInstanceState: Bundle?) {
        setTitleWithBack("个人信息")
        val myname = SpUtils.getInstance().get(Constants.nickName, "") as String
        nickName.text = myname+""
        val headImage = SpUtils.getInstance().get(Constants.headImage, "") as String
        displayImage(headImage,R.drawable.icon_defalut_head,chat_item_header)
        addOnClickListeners(R.id.change_head,R.id.change_nickname)
    }
    override fun getNetWorkData() {
    }

    override fun onResume() {
        super.onResume()
        getmyinfo()
    }

    override fun onClick(v: View?) {
        super.onClick(v)
        when(v!!.id){
            R.id.change_head -> {
                if(isInitPhotoButton || Build.VERSION.SDK_INT < 23){
                    popChangeHeadPanel()
                }else{
                    requestPhotoPermissions()
                }
            }
            R.id.change_nickname -> {
                val intent = Intent(this, ChangeNameActivity::class.java)
                startActivity(intent)
            }
        }
    }

    private fun popChangeHeadPanel() {
        var dialog = IAlertDialog(this, IAlertDialog.LayoutStyle.CHANGEHEAD, Gravity.BOTTOM)
        dialog.setPositiveMsg("从相册中选择")
        dialog.setPositiveOnClickListener { _, _ ->

            if (ContextCompat.checkSelfPermission(
                    this@ChangeNameHeadActivity,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE
                ) != PackageManager.PERMISSION_GRANTED
            ) {
                Toast.makeText(this, "请在应用管理中打开“读写存储”访问权限！", Toast.LENGTH_LONG).show()
            } else {
                openGallery()
            }

        }

        dialog.findViewById<View>(R.id.tocamera).setOnClickListener {
            SelectorHelper.takePhoto(this@ChangeNameHeadActivity, true, 1001)
        }
        dialog.show()
    }


    // 相册
    private fun requestPhotoPermissions() {
        val rxPermission = RxPermissions(this)
        rxPermission.request(
            Manifest.permission.WRITE_EXTERNAL_STORAGE
            , Manifest.permission.WRITE_EXTERNAL_STORAGE
        )
            .subscribe { granted ->
                if (granted!!) {
                    isInitPhotoButton = true
                } else {
                    requestPerFailed(resources.getString(R.string.app_name)+"需要相册权限，请到设置开启权限允许")
                }
            }
    }
    internal var dialog: IAlertDialog? = null
    public fun requestPerFailed(msg:String) {
        dialog = IAlertDialog(this, IAlertDialog.LayoutStyle.THEME_WHITE_TITLE_SINGLEBUTTON, Gravity.CENTER)
        dialog!!.setMessage(msg)
        dialog!!.setPositiveMsg("确定")
        dialog!!.show()
    }
    private fun openGallery() {
        PictureSelector.create(this)
            .openGallery(PictureMimeType.ofImage())
            .maxSelectNum(1)
            .isCamera(false)
            .selectionMode(PictureConfig.SINGLE)
            .forResult(PictureConfig.CHOOSE_REQUEST)
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK) {
            when (requestCode) {
                PictureConfig.CHOOSE_REQUEST -> {
                    // 图片选择结果回调
                    val selectListPic = PictureSelector.obtainMultipleResult(data)
                    for (media in selectListPic) {
                        updateImage(media.path)
                        break
                    }
                }
                1001 ->{
                    val backPics = data?.getStringArrayListExtra(ConstantData.KEY_BACK_PICTURES)
                    if (backPics != null && backPics.size > 0) {
                        updateImage(backPics[0])
                    }
                }
            }
        }

    }

    private fun updateImage(path: String?) {
        var file = File(path)
        if (!file.exists()){
            ToastUtils.showToast("图片选取失败!")
            return
        }
        val param = HashMap<String, String>()
        postDataWithFile("/member/updMemberInfo","headImage",param,file, object : DialogCallback<ResponseBean<AResultBean>>(this) {
            override fun onSuccess(response: Response<ResponseBean<AResultBean>>) {
                ToastUtils.showToast(response.body().msg+"")
                displayImageFile(file,chat_item_header,R.drawable.icon_defalut_head)
            }
        })
    }

    private fun getmyinfo() {
        //隐示获取个人信息
        val param = HashMap<String, String>()
        postData("/member/getMemberInfo",param, object : JsonCallback<ResponseBean<GetUserInfoResultBean>>(this) {
            override fun onSuccess(response: Response<ResponseBean<GetUserInfoResultBean>>) {
                UserUtils.login(response.body().data.memberId+"")
                UserUtils.setUserData(
                    response.body().data.uniqueCode,
                    response.body().data.nickName,
                    response.body().data.headImage,
                    response.body().data.phone
                )
                displayImage(response.body().data.headImage,R.drawable.icon_defalut_head,chat_item_header)
                nickName.text = response.body().data.nickName
            }
        })
    }
}

